<?php

namespace app\privatearea\controller\mall\v2;

use app\common\cachemodel\privatearea\PrivateAreaMallCompany;
use app\common\cachemodel\privatearea\PrivateAreaMallGoods;
use app\common\cachemodel\privatearea\PrivateAreaMallGoodsAttr;
use app\common\cachemodel\privatearea\PrivateAreaMallOrdersRefundRecord;
use app\common\cachemodel\privatearea\PrivateAreaOrders;
use app\common\lib\sfkd\SfKd;
use app\common\lib\Util;
use app\privatearea\controller\MallAuth;
use think\Env;

class Order extends MallAuth
{
    //  订单未支付关闭等待时间
    public $orderPayCloseDelayTime = 300;

    /**
     * 订单列表
     */
    public function orderList()
    {
        $page = input('page/d', 1);

        $page = $page < 1 ? 1 : $page;

        $data = (new PrivateAreaOrders())->getOrderList2($this->user['id'], $page);
        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $orderId = input('order_id/s', '');
        if (!$orderId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $privateAreaOrdersModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrdersModel->getInfoById($orderId);
        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }
        if ($orderInfo['status'] === 1 && $this->request->time() - $orderInfo['create_time'] > $this->orderPayCloseDelayTime + 30)
        {   // 待支付 并且 过了可支付时间 并且还没有关闭订单  进行关闭订单处理
            $orderInfo['status'] = 3;
            $orderInfo['success_time'] = $this->request->time();
            $privateAreaOrdersModel->updateOrderInfo($orderId, ['status' => 3, 'success_time' => $orderInfo['success_time']]);
        }
        $extend = $orderInfo['extend'] ? json_decode($orderInfo['extend'], true) : [];
        if ($orderInfo['status'] === 6 && $this->request->time() - $extend['kd']['send_time'] > 864000)
        {   // 已发货 等待收货 发货后 10天自动完成订单
            $orderInfo['status'] = 4;
            $orderInfo['success_time'] = $extend['kd']['send_time'] + 864000;
            $privateAreaOrdersModel->updateOrderInfo($orderId, ['status' => 4, 'success_time' => $orderInfo['success_time']]);
        }
        $progressData = null;
        if (!in_array($orderInfo['status'], [1, 3], false))
        {   // 1=>待支付 2=>待解答|待发货  3=>未支付订单关闭 4=>已完成 5=>已退款 6=>待收货
            $statusDescTip = $privateAreaOrdersModel->getStatusTip($orderInfo);
            $progressData = [
                'status_desc' => $statusDescTip['des'],
                'status_tip' => $statusDescTip['tip'],
                'kd_num' => $extend['kd']['id'] ?: $orderInfo['waybill_no'],
            ];
        }
        $privateAreaMallGoodsModel = new PrivateAreaMallGoods();
        $privateAreaMallGoodsAttrModel = new PrivateAreaMallGoodsAttr();
        $goodAttrData = $privateAreaMallGoodsAttrModel->getInfoById($orderInfo['qid']);
        $goodData = $privateAreaMallGoodsModel->getInfoById($goodAttrData['gid']);
        $addressData = [
            'id' => $extend['mall']['aid'],
            'phone' => $extend['kd']['phone'],
            'name' => $extend['kd']['name'],
            'address' => $extend['kd']['address'],
        ];
        $payModeList = [];
        if ($orderInfo['status'] === 1)
        {
            $privateAreaMallCompanyModel = new PrivateAreaMallCompany();
            $companyData = $privateAreaMallCompanyModel->getInfoById($extend['mall']['cid']);
            if ($this->isWexinBrowser() && in_array(2, $companyData['pay_type']))
            {
                $payModeList = [
                    [       // 3 => 微信JSAPI支付
                        'trade_type' => 3,
                        'name' => '微信支付',
                        'icon' => '/test/trade_type/trade_type2.png',
                        'is_selected' => 1,
                    ],
                ];
                $payModeList[] = [    // 1=>支付宝H5支付
                    'trade_type' => 1,
                    'name' => '支付宝支付',
                    'icon' => '/test/trade_type/trade_type1.png',
                    'is_selected' => 0,
                ];
            } else
            {
                if (in_array(2, $companyData['pay_type']))
                {
                    $payModeList[] = [ // 2 => 微信H5支付
                        'trade_type' => 2,
                        'name' => '微信支付',
                        'icon' => '/test/trade_type/trade_type2.png',
                        'is_selected' => 1,
                    ];
                }
                if (in_array(1, $companyData['pay_type']))
                {
                    $payModeList[] = [    // 1=>支付宝H5支付
                        'trade_type' => 1,
                        'name' => '支付宝支付',
                        'icon' => '/test/trade_type/trade_type1.png',
                        'is_selected' => 0,
                    ];
                }
            }
        }
        $detailList = [
            [
                'name' => '金额',
                'value' => (float)$orderInfo['total_amount'],
                'type' => 1,
                'key' => '',
                'is_selected' => 0,
            ], [
                'name' => '运费',
                'value' => '包邮',
                'type' => 0,
                'key' => '',
                'is_selected' => 0,
            ],
        ];
        if ($orderInfo['status'] === 1)
        {
            if ($goodData['has_quality_check'])
            {   // 支持 三方质检
                $detailList[] = [
                    'name' => '质检',
                    'value' => '三方质检',
                    'type' => 3,
                    'key' => 'is_check',
                    'is_selected' => $extend['mall']['is_check'] ?? 0,
                ];
            }
            $detailList[] = [
                'name' => '备注',
                'value' => $extend['mall']['remark'] ?? '',
                'type' => 4,
                'key' => 'remark',
                'is_selected' => 0,
            ];
        } else
        {
            if ($goodData['has_quality_check'])
            {   // 支持 三方质检
                $detailList[] = [
                    'name' => '质检',
                    'value' => $extend['mall']['is_check'] ? '走三方质检' : '不走三方质检',
                    'type' => 0,
                    'key' => '',
                    'is_selected' => '',
                ];
            }
            $detailList[] = [
                'name' => '备注',
                'value' => $extend['mall']['remark'] ?? '',
                'type' => 0,
                'key' => '',
                'is_selected' => 0,
            ];
        }
        if (!in_array($orderInfo['status'], [1, 3], true))
        {
            $detailList[] = [
                'name' => '支付方式',
                'value' => $orderInfo['trade_type'] == 1 ? '支付宝支付' : '微信支付',
                'type' => 0,
                'key' => '',
                'is_selected' => 0,
            ];
        }
        $detailList[] = [
            'name' => '下单时间',
            'value' => date('Y-m-d H:i', $orderInfo['create_time']),
            'type' => 0,
            'key' => '',
            'is_selected' => 0,
        ];
        if (in_array($orderInfo['status'], [2, 4, 5, 6], true))
        {   // 1=>待支付 2=>待解答|待发货  3=>未支付订单关闭 4=>已完成 5=>已退款 6=>待收货
            $detailList[] = [
                'name' => '支付时间',
                'value' => date('Y-m-d H:i', $orderInfo['pay_time']),
                'type' => 0,
                'key' => '',
                'is_selected' => 0,
            ];
        }
        $detailList[] = [
            'name' => '订单号',
            'value' => $orderId,
            'type' => 2,
            'key' => '',
            'is_selected' => 0,
        ];
        if ($orderInfo['status'] === 5)
        {   // 已退款
            $detailList[] = [
                'name' => '退款时间',
                'value' => date('Y-m-d H:i', $orderInfo['return_time']),
                'type' => 0,
                'key' => '',
                'is_selected' => 0,
            ];
            $detailList[] = [
                'name' => '退款金额',
                'value' => sprintf("%s元", $orderInfo['return_amount']),
                'type' => 0,
                'key' => '',
                'is_selected' => 0,
            ];
        }
        $btnData = [];
        //1=>可以申请退款 2=>已申请待审核 3=>申请取消 4=>审核失败 5=>审核成功待退款 6=>退款成功
        if (isset($extend['apply_refund']['status'], $extend['apply_refund']['return_type']) && in_array($extend['apply_refund']['return_type'], [3, 4, 5, 6]))
        {   //  'return_type'=> 退货方式  1=>取消发货-公司 2=>取消发货-云仓 3=>拦截物流-公司 4=>拦截物流-云仓 5=>自行寄回-公司 6=>自行寄回-云仓
            if ($extend['apply_refund']['status'] == 1)
            {
                $btnData[] = [
                    'name' => '申请退款',
                    'type' => 5,
                ];
            } else
            {
                $btnData[] = [
                    'name' => '退款详情',
                    'type' => 5,
                ];
            }
        }
        $statusBtn = $privateAreaOrdersModel->getReadStatusBtn($orderInfo['status'], $orderInfo['kd_status'], $extend['kd']['id'] ?: $orderInfo['waybill_no']);
        $btnData = array_merge($btnData, $statusBtn);
        $resData = [
            'progress_data' => $progressData,
            'status' => $orderInfo['status'],
            'img' => $goodAttrData['img'],
            'title' => $goodData['name'],
            'spe_name' => $goodAttrData['name'],
            'sid' => $orderInfo['qid'],
            'gid' => $extend['mall']['gid'],
            'detail_list' => $detailList,
            'address_data' => $addressData,
            'end_pay_time' => $orderInfo['status'] === 1 ? max($this->orderPayCloseDelayTime + $orderInfo['create_time'] - $this->request->time(), 0) : 0,
            'pay_mode_list' => $payModeList,
            'price' => $orderInfo['total_amount'],
            'btn_data' => $btnData,
        ];
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 确认收货
     * @return \think\response\Json
     * @throws \Exception
     */
    public function confirmOrder()
    {
        $orderId = input('order_id/s', '');
        if (!$orderId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $privateAreaOrdersModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrdersModel->getInfoById($orderId);
        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }
        if ($orderInfo['status'] === 6)
        {   // 已发货 等待收货
            $privateAreaOrdersModel->updateOrderInfo($orderId, ['status' => 4, 'success_time' => time()]);
        }
        return show(config('code.success'), '请求成功');
    }

    /**
     * 获取订单快递信息
     * @return \think\response\Json
     * @throws \Exception
     */
    public function orderKdInfo()
    {
        $orderId = input('order_id/s', '');
        $orderInfo = (new PrivateAreaOrders())->getInfoById($orderId);
        if (!$orderInfo || $orderInfo['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }
        $extend = json_decode($orderInfo['extend'], true);
        if (isset($extend['kd']['id']))
        {
            $waybillNo = $extend['kd']['id']?:$orderInfo['waybill_no'];
            if ($orderInfo['shipping_type'] === 1)
            {
                $data = (new SfKd())->getRouteInfo($waybillNo, $extend['kd']['phone']);
                if ($data['status'] === false)
                {
                    return show(config('code.error'), $data['msg']);
                }
                $kdRouteData = current($data['data']);
                $route = $kdRouteData['routes'] ?: [];
                $list = $this->resetKdInfo($orderInfo['kd_status'], $route);
                if (isset($kdRouteData['reasonCode']) && (int)$kdRouteData['reasonCode'] === 20023)
                {
                    $list[] = [
                        'sort' => 10,
                        'title' => '',
                        'content' => ["商家已发货，由于时间过长，无法为您提供该快递的物流信息，具体咨询顺丰快递。"],
                        'tip' => '',
                        'icon' => '',
                    ];
                    $finalArray = $list;
                } else
                {
                    array_multisort(array_column($list, 'sort'), SORT_NUMERIC, SORT_DESC, $list);
                    // 用于存储合并后的数据
                    $mergedData = [];
                    // 用于存储非 "运输中" 的数据
                    $nonTransportData = [];
                    foreach ($list as $item)
                    {
                        if ($item['title'] === '运输中')
                        {
                            $mergedData[] = $item;
                        } else
                        {
                            $nonTransportData[] = $item;
                        }
                    }
                    if ($mergedData)
                    {   // 合并 "运输中" 的内容
                        $mergedContent = array_column($mergedData, 'content');
                        $mergedContentRes = [];
                        foreach ($mergedContent as $item)
                        {
                            $mergedContentRes[] = $item[0];
                        }
                        // 创建新的合并后的数组项
                        $mergedItem = [
                            'sort' => min(array_column($mergedData, 'sort')),
                            'title' => '运输中',
                            'content' => $mergedContentRes,
                            'tip' => '运',
                            'icon' => '',
                        ];
                        // 将合并后的数组项插入到非 "运输中" 的数据中
                        $finalArray = array_merge(array_filter($nonTransportData, function ($item) use ($mergedItem)
                        {
                            return $item['sort'] < $mergedItem['sort'];
                        }), [$mergedItem],
                            array_filter($nonTransportData, function ($item) use ($mergedItem)
                            {
                                return $item['sort'] >= $mergedItem['sort'];
                            })
                        );
                    } else
                    {
                        $finalArray = $list;
                    }
                }
                array_multisort(array_column($finalArray, 'sort'), SORT_NUMERIC, SORT_DESC, $finalArray);
                $kdIcon = '/private_area/sf_kd.png';
            } else
            {   // 云仓发货
                // 调用阿里云市场 快递查询接口 SF3100429570591:4585
                if (strpos($extend['kd']['company'], '顺丰') !== false)
                {
                    $waybillNo .= ':' . substr($extend['kd']['phone'], -4);
                }
                $kdInfo = Util::getKdiInfo($waybillNo, '');
                $list2 = [];
                if (isset($kdInfo['result']['list']))
                {
                    foreach ($kdInfo['result']['list'] as $item)
                    {
                        $list2[] = $item['time'] . ' ' . $item['status'];
                    }
                }
                $finalArray = [];
                if ($list2)
                {
                    $finalArray[] = [
                        'title' => '',
                        'content' => $list2,
                        'tip' => '',
                        'icon' => '',
                    ];
                } elseif ((int)$kdInfo['status'] === 205)
                {
                    $kdType = $extend['kd']['company'] ?? '对应快递公司';
                    $finalArray[] = [
                        'title' => '',
                        'content' => ["商家已发货，由于时间过长，无法为您提供该快递的物流信息，具体咨询{$kdType}。"],
                        'tip' => '',
                        'icon' => '',
                    ];
                }
                $finalArray[] = [
                    'title' => '商品准备中',
                    'content' => ['正在努力备货中...'],
                    'tip' => '',
                    'icon' => '',
                ];
                $kdIcon = '';
            }

            $res = [
                'top' => [
                    'icon' => $kdIcon,
                    'kd_name' => $extend['kd']['company'],
                    'kd_id' => $extend['kd']['id']?:$orderInfo['waybill_no'],
                ],
                'list' => $finalArray,
                'address_info' => [
                    'icon' => '/private_area/kd_receipt.png',
                    'title' => $extend['kd']['address'],
                    'content' => $extend['kd']['name'] . ' ' . substr_replace($extend['kd']['phone'], "****", 3, 4),
                ],
            ];
            return show(config('code.success'), 'success', $res);
        }
        return show(config('code.error'), 'err');
    }

    /**
     * 组合顺丰快递信息
     * @param $kdStatus
     * @param $route
     * @return array
     */
    private function resetKdInfo($kdStatus, $route)
    {
        //kd_status 1=>待下单 2=>待快递员取货 3=>取消发货  50=>已揽件  30=>运输中 44=>派送中 80=>派送成功  70=>派送失败'
        $list = [];
        $sort = 0;
        switch ($kdStatus)
        {
            case 1:
                $list[] = [
                    'sort' => $sort++,
                    'title' => '商品准备中',
                    'content' => ['正在努力备货中...'],
                    'tip' => '备',
                    'icon' => '',
                ];
                break;
            case 2:
                $list[] = [
                    'sort' => $sort++,
                    'title' => '待发货',
                    'content' => ['等待快递揽件中...'],
                    'tip' => '待',
                    'icon' => '',
                ];
                break;
            default:
                if ($kdStatus > 3)
                {
                    $list[] = [
                        'sort' => $sort++,
                        'title' => '商品准备中',
                        'content' => ['正在努力备货中...'],
                        'tip' => '备',
                        'icon' => '',
                    ];
                    $list[] = [
                        'sort' => $sort++,
                        'title' => '待发货',
                        'content' => ['等待快递揽件中...'],
                        'tip' => '待',
                        'icon' => '',
                    ];
                }
                break;
        }

        foreach ($route as $item)
        {
            switch ($item['opCode'])
            {
                case '30': //快件在【XXX营业点】已装车,准备发往 【XXX集散中心】
                case '31': //快件到达 【XXX集散中心】
                case '36': //快件到达 【XXX集散中心】
                case '3036': //快件在XXX ,准备送往下一站
                case '130': //快件到达顺丰店/站
                case '123': //快件正送往顺丰店/站
                case '99': //应客户要求,快件正在转寄中
                    $list[] = [
                        'sort' => $sort++,
                        'title' => '运输中',
                        'content' => [$item['acceptTime'] . ' ' . $item['remark']],
                        'tip' => '运',
                        'icon' => '',
                    ];
                    break;
                case '33': //派件异常原因
                    break;
                case '44': //正在派送途中,请您准备签收(派件人:XXX,电话:XXX)
                case '204': //正在派送途中,请您准备签收(派件人:XXX,电话:XXX)
                    $list[] = [
                        'sort' => $sort++,
                        'title' => '派件中',
                        'content' => [$item['acceptTime'] . ' ' . $item['remark']],
                        'tip' => '取',
                        'icon' => '',
                    ];
                    break;
                case '50': //顺丰已收件
                case '54': //顺丰已收件
                    $list[] = [
                        'sort' => $sort++,
                        'title' => '已揽件',
                        'content' => [$item['acceptTime'] . ' ' . $item['remark']],
                        'tip' => '揽',
                        'icon' => '',
                    ];
                    break;
                case '70': //由于XXX原因 派件不成功
                    break;
                case '80': //已签收,感谢使用顺丰,期待再次为您服务
                case '607': //代理收件
                    $list[] = [
                        'sort' => $sort++,
                        'title' => '已签收',
                        'content' => [$item['acceptTime'] . ' ' . $item['remark']],
                        'tip' => '',
                        'icon' => '/private_area/gou.png',
                    ];
                    break;
                case '8000': //在官网”运单资料&签收图”,可查看签收人信
                    break;
                case '648': //快件已退回/转寄,新单号为: XXX
                    break;
            }
        }
        return $list;
    }

    /**
     * 获取退款信息
     * @return \think\response\Json
     */
    public function getRefundInfo()
    {
        $orderId = input('order_id/s', '');
        if (!$orderId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $privateAreaOrdersModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrdersModel->getInfoById($orderId);
        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }
        $extend = $orderInfo['extend'] ? json_decode($orderInfo['extend'], true) : [];
        if (!$extend || !isset($extend['apply_refund']))
        {
            return show(config('code.error'), '服务异常，退款信息错误～');
        }
        if (!in_array($extend['apply_refund']['return_type'], [3, 4, 5, 6]))
        {
            return show(config('code.error'), '服务异常，退款信息错误～');
        }
        $refundStatus = (int)$extend['apply_refund']['status'];
        //  $extend['apply_refund']['status'] 1=>可以申请退款 2=>已申请待审核 3=>申请取消 4=>审核失败 5=>审核成功待退款 6=>退款成功
        $listData = [];
        if (in_array($extend['apply_refund']['return_type'], [3, 4]))
        {   // //  'return_type'=> 退货方式  1=>取消发货-公司 2=>取消发货-云仓 3=>拦截物流-公司 4=>拦截物流-云仓 5=>自行寄回-公司 6=>自行寄回-云仓
            $listData[] = ['name' => '退货方式', 'style' => 1, 'value' => '拦截', 'placeholder' => '',];
            $listData[] = ['name' => '拦截快递单号', 'style' => 2, 'value' => $extend['kd']['id'] ?: $orderInfo['waybill_no'], 'placeholder' => '',];
        } else
        {
            $listData[] = ['name' => '退货方式', 'style' => 1, 'value' => '寄回', 'placeholder' => '',];
            if (in_array($refundStatus, [1, 3], true))
            {
                $listData[] = ['name' => '填写快递单号', 'style' => 3, 'value' => '', 'placeholder' => '填写快递单号',];
            } else
            {
                $listData[] = ['name' => '填写快递单号', 'style' => 2, 'value' => $extend['apply_refund']['waybill_no'] ?? '', 'placeholder' => '',];
            }
        }
        $listData[] = ['name' => '支付金额', 'style' => 1, 'value' => '¥' . $orderInfo['total_amount'], 'placeholder' => '',];
        $kdFee = 0;
        if (isset($extend['apply_refund']['kd_fee']) && $extend['apply_refund']['kd_fee'])
        {
            $kdFee = (float)$extend['apply_refund']['kd_fee'];
            $listData[] = ['name' => '快递费', 'style' => 1, 'value' => '¥' . $kdFee, 'placeholder' => '',];
        }
        $serviceFee = 0;
        if (isset($extend['apply_refund']['service_fee']) && $extend['apply_refund']['service_fee'])
        {
            $serviceFee = (float)$extend['apply_refund']['service_fee'];
            $listData[] = ['name' => '手续费', 'style' => 1, 'value' => '¥' . $serviceFee, 'placeholder' => '',];
        }
        $refundPrice = (float)($orderInfo['total_amount'] - $kdFee - $serviceFee);
        $refundPrice = max($refundPrice, 0);
        $listData[] = ['name' => '退款金额', 'style' => 1, 'value' => '¥' . $refundPrice, 'placeholder' => '',];
        $returnAddress = null;
        if (in_array($extend['apply_refund']['return_type'], [5, 6]))
        {   // 快递退回地址
            $returnAddress = [
                'title' => '退货地址',
                'name' => $extend['apply_refund']['return_info']['name'] ?? '',
                'tel' => $extend['apply_refund']['return_info']['tel'] ?? '',
                'address' => $extend['apply_refund']['return_info']['address'] ?? '',
            ];
        }

        switch ($refundStatus)
        {   // 1=>可以申请退款 2=>已申请待审核 3=>申请取消 4=>审核失败 5=>审核成功待退款 6=>退款成功
            case 1:
            case 3:
                $btnData = [['name' => '提交申请', 'style' => 1, 'type' => 1,],];
                break;
            case 2:
                $btnData = [
                    [
                        'name' => '已提交，等待到货后审核',
                        'style' => 2,   //  1=>按钮样式【可点击】 2=>按钮样式【不可点击】 3=>无背景样式【取消申请】
                        'type' => 0,   //  0=>点击无效果 1=>提交申请 2=>取消申请
                    ], [
                        'name' => '取消申请',
                        'style' => 3,   //  1=>按钮样式【可点击】 2=>按钮样式【不可点击】 3=>无背景样式【取消申请】
                        'type' => 2,   //  0=>点击无效果 1=>提交申请 2=>取消申请
                    ],
                ];
                break;
            case 4:
                $tipData = ['tip1' => '审核未通过', 'tip2' => "原因：{$extend['apply_refund']['check_reason']}",];
                break;
            case 5:
                $btnData = [['name' => '审核已通过，等待退款', 'style' => 2, 'type' => 0,],];
                break;
            case 6:
                if ((int)$orderInfo['trade_type'] === 1)
                {
                    $btnData = [['name' => '已退款回支付宝账号', 'style' => 2, 'type' => 0,],];
                } else
                {
                    $btnData = [['name' => '已退款回微信账号', 'style' => 2, 'type' => 0,],];
                }
                break;
        }

        $resData = [
            'list' => $listData,
            'status' => in_array($refundStatus, [1, 3], true) ? 1 : 2, // 退款状态 1=>退款申请 2=>退款详情
            'return_address' => $returnAddress,
            'btn_list' => $btnData ?? null,
            'tip_data' => $tipData ?? null,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 申请退款
     * @return \think\response\Json
     */
    public function applyRefund()
    {
        $orderId = input('order_id/s', '');
        $waybillNo = input('waybill_no/s', '');
        if (!$orderId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $privateAreaOrdersModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrdersModel->getInfoById($orderId);
        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }
        $extend = $orderInfo['extend'] ? json_decode($orderInfo['extend'], true) : [];
        if (!$extend || !isset($extend['apply_refund']))
        {
            return show(config('code.error'), '服务异常，退款信息错误～');
        }
        $refundStatus = (int)$extend['apply_refund']['status'];
        if ($refundStatus === 2)
        {
            return show(config('code.error'), '退款申请已提交');
        }
        if (in_array($extend['apply_refund']['return_type'], [5, 6], true))
        {
            if (empty($waybillNo))
            {
                return show(config('code.error'), '请填写快递单号～');
            }
            if (mb_strlen($waybillNo) > 50)
            {
                return show(config('code.error'), '快递单号长度超出限制～');
            }
            $extend['apply_refund']['waybill_no'] = $waybillNo;
        } else
        {
            $waybillNo = '';
        }
        if (!in_array($refundStatus, [1, 3], true))
        {
            return show(config('code.error'), '服务异常，当前状态不可申请退款～');
        }
        $extend['apply_refund']['status'] = 2;
        $refundData = [
            'uid' => $this->user['id'],
            'gaid' => $orderInfo['qid'],
            'waybill_no' => $orderInfo['waybill_no'],
            'return_waybill_no' => $waybillNo,
            'order_id' => $orderId,
            'status' => 1,//1=>等待审核 2=>等待入库 3=>等待退款 4=>审核失败 5=>退款完成 6=>取消申
            'return_type' => $extend['apply_refund']['return_type'],
            'create_time' => $this->request->time(),
            'extend' => json_encode([
                'apply_refund' => [
                    'kd_fee' => $extend['apply_refund']['kd_fee'],
                    'service_fee' => $extend['apply_refund']['service_fee']
                ]
            ], JSON_UNESCAPED_UNICODE)
        ];
        $reId = (new PrivateAreaMallOrdersRefundRecord())->saveData($refundData);
        if (!$reId)
        {
            return show(config('code.error'), '服务异常，申请退款失败～');
        }
        $extend['apply_refund']['id'] = $reId;
        $res = $privateAreaOrdersModel->updateData($orderId, ['extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)]);
        if ($res)
        {
            return show(config('code.success'), '申请提交成功');
        } else
        {
            return show(config('code.error'), '服务异常，申请退款失败～');
        }
    }

    /**
     * 取消退款
     * @return \think\response\Json
     * @throws \Exception
     */
    public function cancelRefund()
    {
        $orderId = input('order_id/s', '');
        if (!$orderId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $privateAreaOrdersModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrdersModel->getInfoById($orderId);
        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }
        $extend = $orderInfo['extend'] ? json_decode($orderInfo['extend'], true) : [];
        if (!$extend || !isset($extend['apply_refund']))
        {
            return show(config('code.error'), '服务异常，退款信息错误～');
        }
        $refundStatus = (int)($extend['apply_refund']['status'] ?? 0);
        if ($refundStatus === 3)
        {
            return show(config('code.success'), '取消成功');
        }
        if ($refundStatus !== 2)
        {
            return show(config('code.error'), '服务异常，当前状态不可取消～');
        }
        $extend['apply_refund']['status'] = 3;  // 1=>可以申请退款 2=>已申请待审核 3=>申请取消 4=>审核失败 5=>审核成功待退款 6=>退款成功
        $refundRecordId = $extend['apply_refund']['id'] ?? 0;
        if ($refundRecordId)
        {
            (new PrivateAreaMallOrdersRefundRecord())->updateData($refundRecordId, ['status' => 7, 'update_time' => $this->request->time()]);
        }
        $res = $privateAreaOrdersModel->updateData($orderId, ['extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)]);
        if ($res)
        {
            return show(config('code.success'), '取消成功');
        } else
        {
            return show(config('code.error'), '服务异常，操作失败～');
        }
    }
}
